let app = getApp()
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
const DBLibrary= db.collection('db_library')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    library_name: '',
    library_duration: '',
    library_create_time: '',
    library_id: '',
    text: '', // htmlcss
    type: '', // h5
    openid: '',
    total: 100,
    passline: 60
  },

  addTypeFn(e){
    // console.log(e.currentTarget.dataset.type)
    this.setData({
      type: e.currentTarget.dataset.type
    })
  },

  async submitFn(){
    let openid = wx.getStorageSync('openid');
    if(openid){
      let library_create_time = new Date().getTime();
      let library_id = Math.random().toString().slice(2);
      library_id = library_id + (new Date().getTime().toString().slice(-5));
      let {library_duration, library_name, type ,text, total, passline} = this.data;
      if(library_duration == '' || library_name == '' || type=='' || total == '' || passline == ''){
        wx.showToast({
          title: '输入框不能为空',
          icon: 'none'
        })
        return false;
      }
      else {
        // 
        let obj = await DBLibrary.where({library_name}).count();
        // console.log(obj);//
        if(obj.total == 0){
          await DBLibrary.add({
            data: {
              library_create_time,
              library_id,
              library_duration: parseFloat(library_duration), 
              library_name, 
              type ,
              text, 
              total, 
              passline,
              isShow: false
            }
          })
          .then(
            content => {
              if (content.errMsg == "collection.add:ok") {
                wx.showToast({
                  title: '添加试卷成功。',
                  icon: 'none'
                })

                let d = setTimeout(()=>{
                  wx.navigateTo({
                    url: '../lib/lib',
                  })
                  clearTimeout(d);
                  d = null;
                })
              } else {
                wx.showToast({
                  title: '添加试卷失败。',
                  icon: 'error'
                })
              }
            }
          )
        }
        else {
          wx.showToast({
            title: '名称已存在重复。',
            icon: 'none'
          })
        }
      }
    }
    else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
    // console.log(this.data)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})